package com.zhaotianhao.controller;

import com.alipay.api.AlipayApiException;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfWriter;
import com.zhaotianhao.pojo.Funds;
import com.zhaotianhao.pojo.FundsTarde;
import com.zhaotianhao.pojo.Users;
import com.zhaotianhao.service.FundsService;
import com.zhaotianhao.service.FundsTardeService;
import com.zhaotianhao.util.AlibabapayGateWayUtils;
import com.zhaotianhao.util.FileUtils;
import com.zhaotianhao.util.PDFUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.UUID;


/**
 * @Author Z-7
 * @Date 2022/3/4
 */
@Controller
@RequestMapping("funds")
public class FundsController {
    @DubboReference
    private FundsService fundsService;
    @DubboReference
    private FundsTardeService fundsTardeService;
    @RequestMapping("list")
    public String to_list(Funds funds, @RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "5")int pageSize, Model model){
        PageInfo<Funds> page = fundsService.queryByPage(funds, pageNum, pageSize);
        model.addAttribute("page",page);
        return "funds/funds_list";
    }
    @RequestMapping("to_add")
    public String to_add(Integer id,Model model){
        Funds funds = fundsService.queryById(id);
        model.addAttribute("fund",funds);
        return "funds/funds_add";
    }

    /**
     * 基金详情
     * @param id
     * @return
     */
    @RequestMapping("detail")
    public String detail(Integer id,Model model){
        Funds funds = fundsService.queryDetail(id);
        model.addAttribute("funds",funds);
        return "funds/funds_detail";
    }
    @RequestMapping("add")
    public String taderFund(Integer num, Integer id, HttpServletRequest request){
        Users login_user = (Users) request.getSession().getAttribute("LOGIN_USER");
        if(login_user == null){
            request.setAttribute("message","请登录");
            return "user/user_login";
        }
        Funds funds1 = fundsService.queryById(id);
        FundsTarde tarde = new FundsTarde();
        tarde.setUserId(login_user.getId()).setFundId(id).setPrice(funds1.getPrice() * num).setNum(num);
        fundsTardeService.insert(tarde);
        FundsTarde fundsTarde1 = fundsTardeService.queryByUidFid(login_user.getId(), id);
        return "redirect:../funds/goPay?id="+fundsTarde1.getId();
    }

    /**
     * 去支付
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "goPay",produces = "text/html;charset=utf-8")
    public @ResponseBody String goPay(String id,HttpServletRequest request) throws AlipayApiException {
        Users login_user = (Users) request.getSession().getAttribute("LOGIN_USER");
        if(login_user == null){
            request.setAttribute("message","请登录");
            return "user/user_login";
        }
        FundsTarde fundsTarde = fundsTardeService.queryById(id);
        String payUrl = AlibabapayGateWayUtils.createOrder(id, fundsTarde.getPrice().toString(),"购买基金","购买");
        return payUrl;
    }
    @RequestMapping("callBack")
    public String callBack(HttpServletRequest request,String out_trade_no,String total_amount){
        Users login_user = (Users) request.getSession().getAttribute("LOGIN_USER");
        FundsTarde fundsTarde = fundsTardeService.queryById(out_trade_no);
        fundsTardeService.updateTardeStatus(out_trade_no,1);
        request.setAttribute("tarde",fundsTarde);
        return "ok";
    }
    @RequestMapping("exprotPDF")
    public @ResponseBody void exprotPDF(Integer mode, HttpServletResponse response) throws Exception {
        // 从数据库查询出需要转换的内容
        PageInfo<Funds> page = fundsService.queryByPage(null, 1, 100);
        // 创建一个文档对象
        Document document = new Document();
        // 生成pdf文件名称
        String pdf = UUID.randomUUID().toString() + ".pdf";
        // 建立一个pdf的书写器，跟上面文档建立关系 可以将文档写入磁盘
        PdfWriter writer = PDFUtils.createDoc(document, "d:/mypdf/" + pdf);
        // 文档中要添加的内容  标题 等等
        ArrayList<String> list = new ArrayList<>();
        list.add("基金列表");
        // 通过工具类给文档对象添加并规定字体大小
        PDFUtils.addContent(document,list,20);
        // 给文档对象添加表格，标明表头，实体类中名称，数据来源，页面从左向右偏移量，从下向上偏移量
        PDFUtils.addTable(writer,new String[] {"基金编号","基金名称","基金价格"},new String[] {"id","name","price"},page.getList(),40,600);
        // 一定要先关闭 在添加水印
        document.close();
        writer.close();
        // 添加水印 参数：要作为水印的图片位置，文件输入流(未加水印的位置)，文件输出流(添加完水印的pdf要输出位置)，文字水印
        PDFUtils.markImage("G:\\img\\323743.jpg",new FileInputStream("d:/mypdf/"+ pdf),new FileOutputStream("d:/mypdf1/"+pdf),"版权所有");
        // 下载文件 响应对象，加完水印之后的位置，要生成的文件名，状态(0：导出，1：预览)
        FileUtils.download(response,"d:/mypdf1/"+pdf,"基金列表.pdf",mode);
    }
}
